"""
检查RabbitMQ队列状态
"""
import pika
import json
from config.settings import settings

def check_queue_status():
    """检查队列状态"""
    try:
        # 连接RabbitMQ
        credentials = pika.PlainCredentials('admin', 'admin')
        parameters = pika.ConnectionParameters(
            host='47.122.18.138',
            port=5672,
            credentials=credentials
        )
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        
        # 检查队列
        queue_name = 'order_queue'
        method = channel.queue_declare(queue=queue_name, durable=True, passive=True)
        
        print(f"✅ RabbitMQ连接成功")
        print(f"📋 队列名称: {queue_name}")
        print(f"📊 队列中的消息数量: {method.method.message_count}")
        print(f"👥 消费者数量: {method.method.consumer_count}")
        
        if method.method.message_count > 0:
            print(f"⚠️  队列中有 {method.method.message_count} 条未处理的消息")
            print("💡 请启动消费者处理这些消息:")
            print("   python order_consumer.py")
        else:
            print("✅ 队列中没有待处理的消息")
            
        if method.method.consumer_count == 0:
            print("⚠️  没有活跃的消费者")
            print("💡 请启动消费者:")
            print("   python order_consumer.py")
        else:
            print(f"✅ 有 {method.method.consumer_count} 个活跃的消费者")
        
        connection.close()
        return True
        
    except Exception as e:
        print(f"❌ RabbitMQ连接失败: {e}")
        print("💡 请检查:")
        print("   1. RabbitMQ服务是否启动")
        print("   2. 连接参数是否正确")
        print("   3. 网络连接是否正常")
        return False

def peek_messages():
    """查看队列中的消息（不消费）"""
    try:
        credentials = pika.PlainCredentials('admin', 'admin')
        parameters = pika.ConnectionParameters(
            host='47.122.18.138',
            port=5672,
            credentials=credentials
        )
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        
        queue_name = 'order_queue'
        
        # 获取一条消息但不确认（peek）
        method_frame, header_frame, body = channel.basic_get(queue=queue_name, auto_ack=False)
        
        if method_frame:
            message = json.loads(body.decode('utf-8'))
            print(f"📄 队列中的消息示例:")
            print(f"   订单号: {message.get('order_no', 'N/A')}")
            print(f"   用户ID: {message.get('user_id', 'N/A')}")
            print(f"   商品ID: {message.get('goods_ids', 'N/A')}")
            print(f"   创建时间: {message.get('created_at', 'N/A')}")
            
            # 拒绝消息，重新放回队列
            channel.basic_nack(delivery_tag=method_frame.delivery_tag, requeue=True)
        else:
            print("📄 队列中没有消息")
            
        connection.close()
        
    except Exception as e:
        print(f"❌ 查看消息失败: {e}")

if __name__ == "__main__":
    print("🔍 检查RabbitMQ队列状态...")
    print("=" * 50)
    
    if check_queue_status():
        print("\n" + "=" * 50)
        print("🔍 查看队列中的消息...")
        peek_messages()
    
    print("\n" + "=" * 50)
    print("🎯 解决方案:")
    print("1. 如果队列中有消息但没有消费者，请启动:")
    print("   python order_consumer.py")
    print("2. 如果RabbitMQ连接失败，请检查服务状态")
    print("3. 启动消费者后，刷新订单页面查看订单")
